import Taro from '@tarojs/taro'
import _get from 'lodash/get'
import { get as getGlobal, READ1000_USER_INFO } from '../globalData';

export const HTTP_SERVER = 'https://api.read1000.com' // 正式服务器
// export const HTTP_SERVER = 'https://admin.read1000.com' // 测试服务器
// export const HTTP_SERVER = 'http://192.168.2.114:8080' // 本地服务器
export const WEB_CLIENT_PREFIX = '{webclient}' // 统一web前缀

export function urlFix(url) {
  if (!url || url.startsWith('http')) return url;
  if (url.startsWith('/')) {
    return url.startsWith(HTTP_SERVER) ? url : `${HTTP_SERVER}${url}`;
  }
  return `${HTTP_SERVER}/${url}`;
}

export function fetch(method = 'get', url, data) {
  return Taro.request({
    method,
    url: urlFix(url),
    data,
    header: {
      contentType: 'application/json;charset=utf-8'
    }
  }).then(res => {
    // if (res.statusCode === 200 && !res.data) {
    //   throw '网络错误'
    // }
    if (res.statusCode === 200) {
      return res.data
    }
  })
}

export function get(url, data) {
  return fetch('get', url, data)
}

export function getWithToken(url, data) {

  console.log(_get(getGlobal(READ1000_USER_INFO), 'user', 'organization'))

  return fetch('get', url, {
    ...data,
    token: _get(getGlobal(READ1000_USER_INFO), 'token'),
    userid: _get(getGlobal(READ1000_USER_INFO), ['user', 'user_id']),
    orgid: _get(getGlobal(READ1000_USER_INFO), ['user', 'organization', 'org_id']) || 0,
  })
}

export function post(url, data) {
  const requestDataJsonStr = WEB_CLIENT_PREFIX + JSON.stringify(data)
  return fetch('post', url, requestDataJsonStr)
}

export function postWithToken(url, data) {
  const requestDataJsonStr = WEB_CLIENT_PREFIX + JSON.stringify({
    ...data,
    token: _get(getGlobal(READ1000_USER_INFO), 'token'),
    userid: _get(getGlobal(READ1000_USER_INFO), ['user', 'user_id']),
    orgid: _get(getGlobal(READ1000_USER_INFO), ['user', 'organization', 'org_id']) || 0,
  })
  return fetch('post', url, requestDataJsonStr)
}
